package com.yimi.policyservice.controller;

import com.github.pagehelper.PageHelper;
import com.yimi.policyservice.common.constant.GloabConstant;
import com.yimi.policyservice.entity.base.system.SysUser;
import com.yimi.policyservice.param.BaseParam;
import com.yimi.policyservice.repository.UserRepository;
import com.yimi.policyservice.utils.TokenUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author jack
 */
@Api
public class BaseController {

    @Autowired
    private UserRepository userRepository ;

    /**
     * 获取登录用户Id
     * @return
     */
    protected String userId(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(GloabConstant.tokenName);
        return TokenUtil.parseJWT(token);
    }

    protected SysUser getLoginUser(){
        String userId = userId();
        return userRepository.findById(userId).get();
    }

    protected void handlerPage(){
        HttpServletRequest request = request();
        int page = Integer.valueOf(request.getParameter(GloabConstant.PAGE_NAME));
        int pageSize =Integer.valueOf( request.getParameter(GloabConstant.PAGE_SIZE));
        PageHelper.startPage(page,pageSize);
    }
    protected <T extends BaseParam>void handlerPage(T t){
        try {
            Class<? extends BaseParam> clazz = t.getClass();
            Method pageMethod = clazz.getMethod("get" + GloabConstant.PAGE_NAME.substring(0, 1).toUpperCase() + GloabConstant.PAGE_NAME.substring(1), new Class[]{});
            Method pageSizeMethod = clazz.getMethod("get" + GloabConstant.PAGE_SIZE.substring(0, 1).toUpperCase() + GloabConstant.PAGE_SIZE.substring(1), new Class[]{});

            int page =(Integer) pageMethod.invoke(t, new Class[]{});
            int pageSize =(Integer) pageSizeMethod.invoke(t, new Class[]{});
            ;
            PageHelper.startPage(page,pageSize);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private HttpServletRequest request(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
}
